//
//  SCAppDelegate.m
//  v2ex-iOS
//
//  Created by Singro on 3/17/14.
//  Copyright (c) 2014 Singro. All rights reserved.
//

#import "JrdAppDelegate.h"

#import "JrdRootViewController.h"
#import "JrdLoginViewController.h"

#import <MBProgressHUD.h>

#import <Fabric/Fabric.h>
#import <Crashlytics/Crashlytics.h>
#import "GuidePageViewController.h"
#import "LCCSqliteManager.h"
@interface JrdAppDelegate (){
    LCCSqliteManager *_manager;
}

@property (nonatomic, strong) MBProgressHUD      *HUD;
@property(nonatomic,strong)NSArray *sheetListArray;

@end

@implementation JrdAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Preload StateManager
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    //[V2TopicStateManager manager];
    [JrdSettingManager manager];
    //[V2CheckInManager manager];
    //[SCWeiboManager manager];
    //[SCWeixinManager manager];
    //[V2QuickActionManager manager];
    [JrdSettingManager manager].selectedSectionIndex = 0;//reset select one to 0
    // Configure URLCache capacity
    // Set URLCache to 3MB
    NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:5 * 1024 * 1024
                                                         diskCapacity:3 * 1024 * 1024
                                                             diskPath:nil];
    [NSURLCache setSharedURLCache:URLCache];

    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];

    self.rootViewController = [[GuidePageViewController alloc] init];
    self.window.rootViewController = self.rootViewController;
        
    [self.window makeKeyAndVisible];
    
    [Fabric with:@[CrashlyticsKit]];

    //Create table
    _manager = [LCCSqliteManager shareInstance];
    [_manager openSqliteFile:@"database"];
    
    //建立几张表：课程信息缓存表：
    /* course data
     course id
     course name
     course category
     course type: selectd/available
     course start time
     course end time
     course photo
     reserve
     */
    if(nil == [_manager getSheetDataWithSheet:@"courselist"]){
        Boolean ret = [_manager createSheetWithSheetHandler:^(LCCSqliteSheetHandler *sheet) {
            sheet.sheetName = @"courselist";
            sheet.sheetType = LCCSheetTypeVariable;
            sheet.sheetField = @[@"user_id",@"course_id",@"course_name",@"course_des",@"course_category",@"course_startDate",@"course_endDate",@"icon_url",@"is_operated",@"is_select",@"reserve_1"];
            sheet.sheetFieldType = @[@"TEXT",@"TEXT",@"TEXT",@"TEXT",@"TEXT",@"TEXT",@"TEXT",@"TEXT",@"TEXT",@"TEXT",@"TEXT"];
            //sheet.primaryKey = @[@"course_id"];
        }];
        NSLog(@"ret = %d", ret);
    }

    /* course node data
     node id
     parent id
     node name
     node audio_url
     node doc_url
     node type: chapter/node
     */
    if(nil == [_manager getSheetDataWithSheet:@"nodelist"]){
        Boolean ret = [_manager createSheetWithSheetHandler:^(LCCSqliteSheetHandler *sheet) {
            sheet.sheetName = @"nodelist";
            sheet.sheetType = LCCSheetTypeVariable;
            sheet.sheetField = @[@"node_id",@"user_id",@"node_name",@"node_audiourl",@"node_doc_url",@"node_type",@"node_parentid",
                @"node_total_time",@"node_study_time",@"is_download",@"download_url",@"level_id"];
            sheet.sheetFieldType = @[@"TEXT",@"TEXT",@"TEXT",@"TEXT",@"TEXT",@"TEXT",@"TEXT",@"TEXT", @"TEXT",@"TEXT",@"TEXT",@"TEXT"];
            
        }];
        NSLog(@"ret = %d", ret);
    }
    
    if(nil == [_manager getSheetDataWithSheet:@"question_list"]){
        Boolean ret = [_manager createSheetWithSheetHandler:^(LCCSqliteSheetHandler *sheet) {
            sheet.sheetName = @"question_list";
            sheet.sheetType = LCCSheetTypeVariable;
            sheet.sheetField = @[@"question_id",@"user_id",@"question_node_id",@"question_user_answer",@"question_value"];
            sheet.sheetFieldType = @[@"INTEGER PRIMARY KEY AUTOINCREMENT",@"TEXT",@"TEXT",@"TEXT",@"TEXT"];
        }];
        NSLog(@"ret = %d", ret);
    }

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{

    if (kSetting.themeAutoChange) {
        CGFloat brightness = [UIScreen mainScreen].brightness;
        
        if (brightness < 0.2) {
            kSetting.theme = V2ThemeNight;
        } else {
            kSetting.theme = V2ThemeDefault;
        }
    }
    
}

- (void)applicationWillTerminate:(UIApplication *)application
{
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{

    /*if ([url.scheme isEqualToString:[@"wb" stringByAppendingString:kWeiboAppKey]]) {
        return [WeiboSDK handleOpenURL:url delegate:[SCWeiboManager manager]];
    }
    
    if ([WXApi handleOpenURL:url delegate:[SCWeixinManager manager]]) {
        return YES;
    }
    */
    return YES;
}

#pragma mark - Quick Action

- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
{
    /*dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6. * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if ([shortcutItem.type isEqualToString:V2CheckInQuickAction]) {
            if ([self checkAndLogin]) {
                if ([V2CheckInManager manager].isExpired) {
                    self.HUD = [[MBProgressHUD alloc] initWithView:self.window];
                    self.HUD.removeFromSuperViewOnHide = YES;
                    self.HUD.mode = MBProgressHUDModeIndeterminate;
                    [self.HUD show:YES];
                    [[V2CheckInManager manager] checkInSuccess:^(NSInteger count) {
                        self.HUD.mode = MBProgressHUDModeText;
                        self.HUD.labelText = [NSString stringWithFormat:@"已签到 %zd 天", count];
                        [self.HUD hide:YES afterDelay:2.];
                    } failure:^(NSError *error) {
                        
                    }];
                } else {
                    self.HUD = [[MBProgressHUD alloc] initWithView:self.currentNavigationController.view];
                    self.HUD.removeFromSuperViewOnHide = YES;
                    self.HUD.mode = MBProgressHUDModeText;
                    self.HUD.labelText = @"今天已签到";
                    [self.HUD show:YES];
//                    [self.HUD hide:YES afterDelay:2.];
                }
            }
        }
        
        if ([shortcutItem.type isEqualToString:V2NotificationQuickAction]) {
            if ([self checkAndLogin]) {
                
            }
        }
    });*/
    
    
}

#pragma mark - Status bar touch tracking
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    CGPoint location = [[[event allTouches] anyObject] locationInView:[self window]];
    CGRect statusBarFrame = [UIApplication sharedApplication].statusBarFrame;
    if (CGRectContainsPoint(statusBarFrame, location)) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kStatusBarTappedNotification
                                                            object:nil];
    }
}

#pragma mark - Helper

/*- (BOOL)checkAndLogin
{
    if (nil == [V2DataManager manager].user) {
        
        MBProgressHUD *huds = [[MBProgressHUD alloc] initWithView:self.window];
        huds.removeFromSuperViewOnHide = YES;
        huds.mode = MBProgressHUDModeText;
        huds.labelText = @"请先登录";
        [huds show:YES];
        [huds hide:YES afterDelay:2.];
        [huds setCompletionBlock:^{
            JrdLoginViewController *loginViewController = [[JrdLoginViewController alloc] init];
            [self.rootViewController presentViewController:loginViewController animated:YES completion:^{
                ;
            }];
        }];
        
        return NO;
    }
    
    return YES;
}*/

@end
